package com.sloth.service.impl;

import com.sloth.mapper.CustomerMapper;
import com.sloth.pojo.Customer;
import com.sloth.pojo.CustomerExample;
import com.sloth.service.CustomerService;
import com.sloth.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author lai
 * @time 2021/10/6 9:03
 */
@Service
public class CustomerServiceImpl implements CustomerService {

    private static KeyPair keyPair;

    private final String key = "19win899RSV8e303";

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public Customer getByCustomerId(Integer customerId) {

        return customerMapper.selectByPrimaryKey(customerId);
    }

    @Override
    public ServerResponse login(String username, String password, HttpServletRequest request, HttpServletResponse response) {

        CustomerExample customerExample = new CustomerExample();

        String privateKey = getPrivateKey();

        String encrypt = null;
        try {
            System.out.println("RSA解密中.....");
            String decrypted = RSAUtils.privateDecrypt(password, RSAUtils.getPrivateKey(privateKey));

            System.out.println("RSA解密后：" + decrypted);


            encrypt = AESUtil.encrypt(decrypted, key);

            System.out.println("AES加密后：" + encrypt);

        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            Long usertrl = Long.parseLong(username);
            customerExample.createCriteria().andCustTelnoEqualTo(usertrl).andCustPasswordEqualTo(encrypt);
        } catch (NumberFormatException e) {
            customerExample.createCriteria().andCustEmailEqualTo(username).andCustPasswordEqualTo(encrypt);
        }
        List<Customer> customers = customerMapper.selectByExample(customerExample);

        if (customers.size() > 0) {

            Customer customer = customers.get(0);
            //用户找到了,用户名密码正确,跳转到首页,并在首页中显示用户名
            System.out.println("C用户: " + customer);
            String ticket = UUIDUtils.getUUID();
            System.out.println("ticket:"+ticket);
            redisTemplate.opsForValue().set("customer:" + ticket, customer,60, TimeUnit.MINUTES);

            Cookie cookie = new Cookie("customerTicket", ticket);
            cookie.setPath("/");
            cookie.setHttpOnly(true);
            response.addCookie(cookie);

            return ServerResponse.getSuccess("登陆成功");

        } else {
            System.out.println("跳到login");
            return ServerResponse.getFail("用户名或密码错误,请重新输入");
        }
    }

    @Override
    public ServerResponse register(Customer customer) {
        customer.setCustNickname("user_" + customer.getCustTelno());
        customer.setCustGender("F");
        customer.setCustHead("../images/customer/head.jpg");
        customer.setCystCart(0);
        customer.setState(0);

        // 获取密文
        String encrypted = customer.getCustPassword();
        // 获取私钥
        String privateKey = getPrivateKey();

        try {
            // String 太长了


            System.out.println("RSA解密中.....");
            // 原密码 = 解密方法（密文，私钥）
            String decrypted = RSAUtils.privateDecrypt(encrypted, RSAUtils.getPrivateKey(privateKey));

            //
            System.out.println("RSA解密后：" + decrypted);


            // AES 加密
            String encrypt = AESUtil.encrypt(decrypted, key);

            System.out.println("AES加密后：" + encrypt);
            customer.setCustPassword(encrypt);

        } catch (Exception e) {
            e.printStackTrace();
        }

        int rows = customerMapper.insert(customer);
        if (rows > 0) return ServerResponse.saveSuccess(rows);
        else return ServerResponse.saveFail(rows);
    }

    @Override
    public ServerResponse getPublicKey() {
//        KeyPair keyPair= null;
        try {
            // 创建密钥对
            keyPair = RSAUtils.genKeyPair(1024);
            // 获取公钥
            PublicKey publicKey = keyPair.getPublic();

            System.out.println("公钥：");

            String pubKey = new String(Base64.getEncoder().encode(publicKey.getEncoded()));
            System.out.println(pubKey);

            return ServerResponse.getSuccess(pubKey);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ServerResponse.getFail(null);

    }

    @Override
    public String getPrivateKey() {
        try {
            PrivateKey privateKey = keyPair.getPrivate();
            System.out.println("get私钥：");

            // 输出String私钥
            String priKey = new String(Base64.getEncoder().encode(privateKey.getEncoded()));
            System.out.println(priKey);

            return priKey;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    @Override
    public Object getPersonCard(MultipartFile multipartFile) {


        return null;
    }

    @Override
    public void createCustomer(int count) {

        for (int i = 0; i < count; i++) {
//            long date =new Date().getTime();
            long tel = 13000000000l + i;
            Customer customer = new Customer();
            customer.setCustTelno(tel);
            customer.setCustNickname("user_" + tel);
            customer.setCustGender("F");
            customer.setCustPassword("U0Qsk1UMwSq82VkoU3jy0g==");
            customer.setCustEmail("" + tel + "@qq.com");
            customer.setCustHead("../images/customer/head.jpg");
            customer.setCystCart(0);
            customer.setState(0);
            customerMapper.insert(customer);
        }
        System.out.println("create Customer");
    }

    @Override
    public Customer getCustomerByCookie(String customerTicket, HttpServletRequest request, HttpServletResponse response) {
        if (customerTicket == null) {
            return null;
        }
        System.out.println("customerTicket:"+customerTicket);
        Customer customer = (Customer) redisTemplate.opsForValue().get("customer:" + customerTicket);
//        if (customer == null) {
//
//            return null;
//        }
        return customer;
    }
}